// 库存查询页面

import React, {Component} from 'react';
import {DeviceEventEmitter, StatusBar, Text, View, Image, TouchableWithoutFeedback, TouchableNativeFeedback, ScrollView, TouchableOpacity, StyleSheet, TextInput, FlatList} from 'react-native';
import styles, {mainBackgroundColor, white} from "../../../style/global";
import storeActions from '../../../store/actions/store';
import {bindActionCreators} from 'redux';
import {is, fen_to_yuan, fen_money, getNowFormatDate} from '../../../utils';
import {Actions} from "react-native-router-flux";
import {connect} from "react-redux";
import NavBar from '../../widget/navBar';
import CXIcon from '../../../style/icon/CXIcon';
import ModalDropdown from 'react-native-modal-dropdown';
import InventoryPage from "./inventory";
import TransferPage from "./transfer";

class stockPage extends Component{
    constructor(props){
        super(props);
        this.stockPage = 1;
        this.state = {
            isLoadMore:false,
            activeIndex:0,
            searchVal:'',
            meta: {
                store_nums: '',
                purchaseAmount: ''
            },
            currentShop: '', // 当前店铺
            currentYears: {
                id: '',
                name: '全部年份'
            },
            currentSeasons: {
                id: '',
                name: '全部季节'
            },
            currentAllCategories: {
                id: '',
                name: '全部分类'
            },
            currentBrandList: {
                id: '',
                name: '全部品牌'
            },
            navItem: [
                {
                    icon: 'xiaoshoudanju',
                    name: '采购入库',
                    key: 'ProductDataPage'
                },
                {
                    icon: 'kucunchaxun',
                    name: '采购退货',
                    key: 'ProductDataPage'
                },
                {
                    icon: 'kucunchaxun',
                    name: '库存盘点',
                    key: 'InventoryPage'
                },
                {
                    icon: 'kucunchaxun',
                    name: '库存调拨',
                    key: 'TransferPage'
                }
            ],
        };
    }
    componentDidMount(){
        storage.load({
            key: 'clerk-info'
        }).then(res => {
            if (res && res.shops) {
                this.setState({
                    currentShop: res.shops
                });
            }
        }).catch(err => {

        });
        let {storeAction} = this.props;
        storeAction.getStockList(1);
        storeAction.getShopList();
        this.listener = DeviceEventEmitter.addListener('stockHasMore',(isLoadMore, meta) => {
            console.log('这个是meta', meta);
            this.setState({
                isLoadMore:isLoadMore,
                meta: meta
            })
        })
    }
    componentWillUnmount() {
        this.listener.remove();
    }
    //创建空布局
    _createEmptyView(){
        return (
            <View style={{height:'100%', alignItems:'center', justifyContent:'center',paddingVertical: 20}}>
                <Text style={{fontSize:16}}>
                    暂无列表数据!!!
                </Text>
            </View>
        );
    }
    _clickItem(item, index) {
        if (item && item.key) {
            Actions.push(item.key, {
                title: item.name
            });
        }
    }
    _searchStock(){
        let {storeAction} = this.props;
        storeAction.getStockList(1,this.state.currentShop.id, this.state.currentYears.id, this.state.currentSeasons.id, this.state.currentAllCategories.id, this.state.currentBrandList.id, true,this.state.searchVal, res => {
            console.log('这个是返回的', res);
            if (res && res.status) {
                this.setState({
                    meta: res.meta
                })

            }
        });
    }
    //加载更多
    _onLoadMore(){
        if(this.state.isLoadMore){
            this.stockPage = this.stockPage + 1;
            let {storeAction} = this.props;
            storeAction.getStockList(this.stockPage,this.state.currentShop.id, this.state.currentYears.id, this.state.currentSeasons.id, this.state.currentAllCategories.id, this.state.currentBrandList.id, false, this.state.searchVal);
        }
    }
    _shopNode(option, index, isSelected) {
        return (
            <Text style={{padding: 5, width: 100}}>
                {option.name}
            </Text>
        );
    }
    _categories(option, index, isSelected) {
        if (option.level == 2) {
            return (
                <Text style={{padding: 5, width: 100, marginLeft: 10}}>
                    {option.name}
                </Text>
            );
        } else {
            return (
                <Text style={{padding: 5, width: 100}}>
                    {option.name}
                </Text>
            );
        }
    }
    // 店铺显示文本
    _shopTextNode(option) {
        return option.name;
    }

    // 选择店铺
    _selectShop(index, item, type) {
        if (item) {
            this.setState({
                [`${type}`]: item
            })
        }
    }
    // 库存金额渲染
    _purchaseAmountNode() {
        if (this.state.currentShop && this.state.currentShop.is_clerk_owner) {
            return (
                <Text>
                    库存金额：￥{this.state.meta.purchaseAmount}
                </Text>
            )
        }
    }
    //渲染库存列表
    _renderStockList(rowData,index){
        return(
            <TouchableNativeFeedback>
                <View style={style.listItem}>
                    <Text style={[style.listItemText]}>
                        {rowData.base_goods.goods_no}
                    </Text>
                    <Text style={[style.listItemText]}>
                        {rowData.base_goods.name}；{rowData.spec_text}
                    </Text>
                    <Text style={[style.listItemText, style.flex1]}>
                        ¥ {rowData.base_goods.market_price}
                    </Text>
                    <Text style={[style.listItemText, style.flex1]}>
                        {rowData.store_nums}
                    </Text>
                </View>
            </TouchableNativeFeedback>
        )
    }
    render() {
        let{storeState} = this.props;
        return (
            <View>
                <StatusBar hidden={true}/>

                {/*顶部导航*/}
                <NavBar
                    navItem={this.state.navItem}
                    onPressItem={(item, index) => this._clickItem(item, index)}
                >
                </NavBar>
                <View style={style.search}>
                    <View style={style.selectBox}>
                        <View style={style.dropDownBox}>
                            <ModalDropdown style={style.dropDown} textStyle={{color: '#909090', fontSize: 14}} defaultValue={this.state.currentShop ? this.state.currentShop.name : '请选择店铺'} options={storeState.shopList.shops} renderRow={(option, index, isSelected) => this._shopNode(option, index, isSelected)} renderButtonText={(option) => this._shopTextNode(option)} onSelect={(index, item) => this._selectShop(index, item, 'currentShop')}>

                            </ModalDropdown>
                            <CXIcon name='xiala' size={10} color={'#909090'}>

                            </CXIcon>
                        </View>
                        <View style={style.dropDownBox}>
                            <ModalDropdown style={style.dropDown} textStyle={{color: '#909090', fontSize: 14}} defaultValue={this.state.currentYears ? this.state.currentYears.name : '请选择年份'} options={storeState.shopList.years} renderRow={(option, index, isSelected) => this._shopNode(option, index, isSelected)} renderButtonText={(option) => this._shopTextNode(option)} onSelect={(index, item) => this._selectShop(index, item, 'currentYears')}>

                            </ModalDropdown>
                            <CXIcon name='xiala' size={10} color={'#909090'}>

                            </CXIcon>
                        </View>
                        <View style={style.dropDownBox}>
                            <ModalDropdown style={style.dropDown} textStyle={{color: '#909090', fontSize: 14}} defaultValue={this.state.currentSeasons ? this.state.currentSeasons.name : '请选择季节'} options={storeState.shopList.seasons} renderRow={(option, index, isSelected) => this._shopNode(option, index, isSelected)} renderButtonText={(option) => this._shopTextNode(option)} onSelect={(index, item) => this._selectShop(index, item, 'currentSeasons')}>

                            </ModalDropdown>
                            <CXIcon name='xiala' size={10} color={'#909090'}>

                            </CXIcon>
                        </View>
                        <View style={style.dropDownBox}>
                            <ModalDropdown style={style.dropDown} textStyle={{color: '#909090', fontSize: 14}} defaultValue={this.state.currentAllCategories ? this.state.currentAllCategories.name : '请选择分类'} options={storeState.shopList.allCategories} renderRow={(option, index, isSelected) => this._categories(option, index, isSelected)} renderButtonText={(option) => this._shopTextNode(option)} onSelect={(index, item) => this._selectShop(index, item, 'currentAllCategories')}>

                            </ModalDropdown>
                            <CXIcon name='xiala' size={10} color={'#909090'}>

                            </CXIcon>
                        </View>
                        <View style={[style.dropDownBox, {borderRightWidth: 0}]}>
                            <ModalDropdown style={style.dropDown} textStyle={{color: '#909090', fontSize: 14}} defaultValue={this.state.currentBrandList ? this.state.currentBrandList.name : '请选择品牌'} options={storeState.shopList.brandList} renderRow={(option, index, isSelected) => this._shopNode(option, index, isSelected)} renderButtonText={(option) => this._shopTextNode(option)} onSelect={(index, item) => this._selectShop(index, item, 'currentBrandList')}>

                            </ModalDropdown>
                            <CXIcon name='xiala' size={10} color={'#909090'}>

                            </CXIcon>
                        </View>
                        <TextInput
                            style={style.searchInput}
                            onChangeText={(searchVal) => this.setState({searchVal})}
                        />
                        <TouchableWithoutFeedback onPress={() => {this._searchStock()}}>
                            <View>
                                <Text style={style.searchText}>搜索</Text>
                            </View>
                        </TouchableWithoutFeedback>
                    </View>
                    <View>
                        <Text>
                            库存总数：{this.state.meta.store_nums}
                        </Text>
                        {this._purchaseAmountNode()}
                    </View>
                </View>
                <View style={style.list}>
                    <View style={style.listItem}>
                        <Text style={[style.listItemText, style.titleColor]}>
                            货号
                        </Text>
                        <Text style={[style.listItemText, style.titleColor]}>
                            品名
                        </Text>
                        <Text style={[style.listItemText, style.titleColor, style.flex1]}>
                            单价
                        </Text>
                        <Text style={[style.listItemText, style.titleColor, style.flex1]}>
                            库存
                        </Text>
                    </View>
                    <View>
                        <FlatList
                            style={{height: 500}}
                            keyExtractor={(item, index) => index.toString()}
                            data={storeState.stockList}
                            renderItem={({item,index}) => this._renderStockList(item,index)}
                            onEndReached = {()=> this._onLoadMore()}
                            onEndReachedThreshold={0.1}
                            extraData={storeState.stockList}
                            ListEmptyComponent={this._createEmptyView}
                        >
                        </FlatList>
                    </View>

                </View>
            </View>
        )
    }
}

const style = StyleSheet.create({
    search: {
      height: '13%',
        paddingHorizontal: 30,
        flexDirection: 'row',
      alignItems: 'center',
    },
    selectBox: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1
    },
    searchInput: {
        width: 320,
        backgroundColor: white,
        paddingHorizontal: 10,
        height: 44,

    },
    searchText: {
        width: 70,
        textAlign: 'center',
        lineHeight: 44,
        backgroundColor: mainBackgroundColor,
        color: white
    },
    list: {
        height: '87%',
        backgroundColor: white,
        paddingHorizontal: 30
    },
    listItem: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 15,
        borderBottomWidth: 1,
        borderColor: '#F0F0F5'
    },
    listItemText: {
        flex: 2,
        fontSize: 14,
        color: '#4A4A4A'
    },
    titleColor: {
       color: '#909090'
    },
    flex1: {
        flex: 1
    },
    itemRight: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1
    },
    dropDown: {
        // width: 120,
        paddingRight: 12
    },

    dropDownBox: {
        width: 120,
        // backgroundColor: '#F3F3F3',
        height: 44,
        // width: 100,
        // borderRadius: 4,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        // padding: 12,
        marginRight: 5,
        borderRightWidth: 1,
        borderColor: '#D8D8D8'
    },
});

export default connect(state =>({
    storeState: state.store
}),dispatch =>({
    storeAction: bindActionCreators(storeActions,dispatch)
}))(stockPage);
